﻿using ServiceMonitor.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServiceMonitor.Forms
{
    public partial class FrmMonitorEditor : Form
    {

        private readonly MonitorConfig _originalConfig;
        public MonitorConfig Config { get; private set; }

        // HTTP健康 设置控件
        private TextBox txtUrl;
        private NumericUpDown numTimeout;
        private NumericUpDown numExpectedStatus;

        // 端口设置控件
        private TextBox txtHost;
        private NumericUpDown numPort;

        // SpringBoot 设置控件
        private TextBox txtJarPath;
        private Button btnBrowse;
        private TextBox txtJavaArgs;
        private TextBox txtWorkDir;
        private NumericUpDown txtHttpPort;
        private Button btnBrowseWorkDir;

        public FrmMonitorEditor(MonitorConfig config)
        {
            _originalConfig = config;
            Config = config;

            InitializeComponent();

            InitializeUI();
            InitializeTypeSpecificControls();
            LoadConfigIntoControls();

            // 设置最小尺寸
            this.MinimumSize = new Size(650, 400);
        }

        private void InitializeUI()
        {
            this.Text = "编辑监控项";
            //this.Size = new Size(650, 500);
            this.Font = new Font("Segoe UI", 9);
            this.StartPosition = FormStartPosition.CenterParent;
            this.BackColor = SystemColors.Window;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;


            cmbType.SelectedIndexChanged += CmbType_SelectedIndexChanged;
            btnSave.Click += SaveConfig;


            // ============= 第四行：占位区 =============
            // 使用Panel占据空间
            var spacer = new Panel { Dock = DockStyle.Fill };

            // ============= 第五行：按钮区域 =============
            var btnPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 40,
                Padding = new Padding(0, 10, 0, 0)
            };

            btnSave = new Button
            {
                Text = "保存",
                Size = new Size(90, 30),
                Anchor = AnchorStyles.Right,
                DialogResult = DialogResult.OK
            };
            btnSave.Click += SaveConfig;

            btnCancel = new Button
            {
                Text = "取消",
                Size = new Size(90, 30),
                Location = new Point(btnSave.Left - 100, btnSave.Top),
                Anchor = AnchorStyles.Right,
                DialogResult = DialogResult.Cancel
            };



            // ============= 添加到主表格 =============


        }

        private void InitializeTypeSpecificControls()
        {
            // 端口监控设置
            var portPanel = CreatePortSettings();
            portPanel.Visible = false;
            grpTypeSettings.Controls.Add(portPanel);

            // HTTP监控设置
            var httpPanel = CreateHttpSettings();
            httpPanel.Visible = false;
            grpTypeSettings.Controls.Add(httpPanel);

            // JAR监控设置
            var jarPanel = CreateJarSettings();
            jarPanel.Visible = false;
            grpTypeSettings.Controls.Add(jarPanel);
        }

        private Panel CreatePortSettings()
        {
            var panel = new Panel { Dock = DockStyle.Fill, Name = "portPanel" };
            var layout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 2,
                Padding = new Padding(5)
            };

            // 主机设置
            layout.Controls.Add(new Label { Text = "主机:", TextAlign = ContentAlignment.MiddleRight }, 0, 0);
            txtHost = new TextBox { Dock = DockStyle.Fill, Text = "localhost" };
            layout.Controls.Add(txtHost, 1, 0);

            // 端口设置
            layout.Controls.Add(new Label { Text = "端口:", TextAlign = ContentAlignment.MiddleRight }, 0, 1);
            numPort = new NumericUpDown
            {
                Dock = DockStyle.Fill,
                Minimum = 1,
                Maximum = 65535,
                Value = 80
            };
            layout.Controls.Add(numPort, 1, 1);

            panel.Controls.Add(layout);
            return panel;
        }

        private Panel CreateHttpSettings()
        {
            var panel = new Panel { Dock = DockStyle.Fill, Name = "httpPanel" };
            var layout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 3,
                Padding = new Padding(5)
            };

            // URL设置
            layout.Controls.Add(new Label { Text = "URL:", TextAlign = ContentAlignment.MiddleRight }, 0, 0);
            txtUrl = new TextBox { Dock = DockStyle.Fill, Text = "http://" };
            layout.Controls.Add(txtUrl, 1, 0);

            // 超时设置
            layout.Controls.Add(new Label { Text = "超时(毫秒):", TextAlign = ContentAlignment.MiddleRight }, 0, 1);
            numTimeout = new NumericUpDown
            {
                Dock = DockStyle.Fill,
                Minimum = 100,
                Maximum = 60000,
                Value = 5000
            };
            layout.Controls.Add(numTimeout, 1, 1);

            // 状态码设置
            layout.Controls.Add(new Label { Text = "预期状态码:", TextAlign = ContentAlignment.MiddleRight }, 0, 2);
            numExpectedStatus = new NumericUpDown
            {
                Dock = DockStyle.Fill,
                Minimum = 100,
                Maximum = 599,
                Value = 200
            };
            layout.Controls.Add(numExpectedStatus, 1, 2);

            panel.Controls.Add(layout);
            return panel;
        }

        private Panel CreateJarSettings()
        {
            var panel = new Panel { Dock = DockStyle.Fill, Name = "jarPanel" };
            //  创建布局控件，3列，5行
            var layout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 3,
                RowCount = 5,
                Padding = new Padding(5)
            };
            // 列宽设置
            layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20F));
            layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 65F));
            layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 15F));

            // JAR 路径
            // 在 TableLayoutPanel 的第 0 列第 0 行添加一个 Label，显示文本 "JAR路径:"，文字右对齐。
            layout.Controls.Add(new Label { Text = "JAR路径:", TextAlign = ContentAlignment.MiddleRight }, 0, 0);
            txtJarPath = new TextBox { Dock = DockStyle.Fill };
            // 将 txtJarPath 添加到 TableLayoutPanel 的第 1 列第 0 行。
            layout.Controls.Add(txtJarPath, 1, 0);

            btnBrowse = new Button { Text = "浏览...", Dock = DockStyle.Fill };
            btnBrowse.Click += BtnBrowse_Click;
            // 将 btnBrowse 添加到 TableLayoutPanel 的第 2 列第 0 行。
            layout.Controls.Add(btnBrowse, 2, 0);
            // 设置 btnBrowse 跨越 1 行（默认值，可省略）。
            layout.SetRowSpan(btnBrowse, 1);

            // 工作目录
            layout.Controls.Add(new Label { Text = "工作目录:", TextAlign = ContentAlignment.MiddleRight }, 0, 1);
            txtWorkDir = new TextBox { Dock = DockStyle.Fill };
            layout.Controls.Add(txtWorkDir, 1, 1);

            btnBrowseWorkDir = new Button { Text = "浏览...", Dock = DockStyle.Fill };
            btnBrowseWorkDir.Click += BtnBrowseWorkDir_Click;
            layout.Controls.Add(btnBrowseWorkDir, 2, 1);

            // SpringBoot http端口
            layout.Controls.Add(new Label { Text = "Port:", TextAlign = ContentAlignment.MiddleRight }, 0, 2);
            txtHttpPort = new NumericUpDown { Dock = DockStyle.Fill, Maximum = 65000, Minimum = 80, Text = "8080" };
            layout.Controls.Add(txtHttpPort, 1, 2);
            layout.SetColumnSpan(txtHttpPort, 2);

            // Java参数
            layout.Controls.Add(new Label { Text = "Java参数:", TextAlign = ContentAlignment.MiddleRight }, 0, 3);
            txtJavaArgs = new TextBox { Dock = DockStyle.Fill, Text = "-Xmx512m" };
            layout.Controls.Add(txtJavaArgs, 1, 3);
            layout.SetColumnSpan(txtJavaArgs, 2);

            // 信息提示
            var infoLabel = new Label
            {
                Text = "提示: 空工作目录将使用JAR所在文件夹",
                ForeColor = SystemColors.GrayText,
                Dock = DockStyle.Fill
            };
            layout.Controls.Add(infoLabel, 0, 4);
            layout.SetColumnSpan(infoLabel, 2);

            panel.Controls.Add(layout);
            return panel;
        }

        private void LoadConfigIntoControls()
        {
            txtName.Text = Config.Name;
            chkActive.Checked = Config.IsActive;
            numInterval.Value = Config.CheckInterval;

            chkEmailAlert.Checked = Config.EnableEmailAlert;
            txtEmail.Text = Config.AlertEmail;

            // 设置监控类型
            switch (Config.Type)
            {
                case MonitorType.Port:
                    cmbType.SelectedIndex = 0;
                    break;

                case MonitorType.Http:
                    cmbType.SelectedIndex = 1;
                    break;

                case MonitorType.StringBoot:
                    cmbType.SelectedIndex = 2;
                    break;
                default:
                    cmbType.SelectedIndex = 0;
                    break;
            }


            // 加载类型特定配置
            switch (Config.Type)
            {
                case MonitorType.Port:
                    txtHost.Text = Config.Host;
                    numPort.Value = Config.Port;
                    break;

                case MonitorType.Http:
                    txtUrl.Text = Config.Url;
                    numTimeout.Value = Config.Timeout;
                    numExpectedStatus.Value = Config.ExpectedStatus == HttpStatusCode.OK ? (int)HttpStatusCode.OK : (int)Config.ExpectedStatus;
                    break;

                case MonitorType.StringBoot:
                    txtJarPath.Text = Config.JarPath;
                    txtJavaArgs.Text = Config.JavaArgs;
                    txtHttpPort.Value = Config.Port;
                    txtWorkDir.Text = Config.WorkingDirectory;
                    break;
            }

            // 确保显示正确的面板
            ShowTypeSpecificPanel(cmbType.SelectedIndex);
        }

        private void CmbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowTypeSpecificPanel(cmbType.SelectedIndex);
        }

        private void ShowTypeSpecificPanel(Int32 index)
        {
            // 隐藏所有面板
            foreach (Control ctrl in grpTypeSettings.Controls)
            {
                ctrl.Visible = false;
            }
            string panelName = "httpPanel";

            // 显示选中的面板
            switch (index)
            {
                case 0:
                    panelName = "portPanel";
                    break;
                case 1:
                    panelName = "httpPanel";
                    break;
                case 2:
                    panelName = "jarPanel";
                    break;
            }

            var panel = grpTypeSettings.Controls[panelName];
            if (panel != null)
            {
                panel.Visible = true;
                panel.BringToFront();
            }
        }

        private void SaveConfig(Object sender, EventArgs e)
        {
            // 验证基本设置
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("请填写服务名称", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtName.Focus();
                return;
            }

            // 验证类型设置
            switch (cmbType.SelectedIndex)
            {
                case 0: // 端口
                    if (string.IsNullOrWhiteSpace(txtHost.Text))
                    {
                        MessageBox.Show("请填写主机地址", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtHost.Focus();
                        return;
                    }
                    break;

                case 1: // HTTP
                    if (string.IsNullOrWhiteSpace(txtUrl.Text) || !txtUrl.Text.StartsWith("http"))
                    {
                        MessageBox.Show("请输入有效的URL地址", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtUrl.Focus();
                        return;
                    }
                    break;

                case 2: // JAR
                    if (string.IsNullOrWhiteSpace(txtJarPath.Text))
                    {
                        MessageBox.Show("请选择JAR文件", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    break;
            }

            // 保存基本设置
            Config.Name = txtName.Text;
            Config.IsActive = chkActive.Checked;
            Config.CheckInterval = (Int32)numInterval.Value;

            // 保存告警设置
            Config.EnableEmailAlert = chkEmailAlert.Checked;
            Config.AlertEmail = txtEmail.Text;

            // 保存类型设置
            MonitorType newType = MonitorType.Http;


            switch (cmbType.SelectedIndex)
            {
                case 0: newType = MonitorType.Port; break;
                case 1: newType = MonitorType.Http; break;
                case 2: newType = MonitorType.StringBoot; break;
                default:
                    newType = MonitorType.Http; break;
            }
            ;

            Config.Type = newType;

            // 保存类型特定设置
            switch (newType)
            {
                case MonitorType.Port:
                    Config.Host = txtHost.Text;
                    Config.Port = (Int32)numPort.Value;
                    Config.Url = null;
                    Config.JarPath = null;
                    break;

                case MonitorType.Http:
                    Config.Url = txtUrl.Text;
                    Config.Timeout = (Int32)numTimeout.Value;
                    Config.ExpectedStatus = (HttpStatusCode)numExpectedStatus.Value;
                    Config.Host = null;
                    Config.Port = 80;
                    Config.JarPath = null;
                    break;

                case MonitorType.StringBoot:
                    Config.JarPath = txtJarPath.Text;
                    Config.JavaArgs = txtJavaArgs.Text;
                    Config.WorkingDirectory = txtWorkDir.Text;
                    Config.Port = (Int32)txtHttpPort.Value;
                    break;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void BtnBrowse_Click(object sender, EventArgs e)
        {
            using (var dialog = new OpenFileDialog())
            {
                dialog.Filter = "JAR文件|*.jar|所有文件|*.*";
                dialog.Title = "选择JAR文件";
                dialog.CheckFileExists = true;
                dialog.Multiselect = false;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    txtJarPath.Text = dialog.FileName;

                    // 如果工作目录为空，自动设置为JAR父目录
                    if (string.IsNullOrWhiteSpace(txtWorkDir.Text))
                    {
                        txtWorkDir.Text = Path.GetDirectoryName(dialog.FileName);
                    }
                }
            }
        }

        private void BtnBrowseWorkDir_Click(object sender, EventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择工作目录";
                dialog.ShowNewFolderButton = true;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    txtWorkDir.Text = dialog.SelectedPath;
                }
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            // 捕获Esc键关闭窗口
            if (keyData == Keys.Escape)
            {
                this.Close();
                return true;
            }
            return base.ProcessDialogKey(keyData);
        }
    }
}
